// 3D场景模拟组件 - 基于用户需求说明的实时三维场景功能

import React, { useState } from 'react';
import { useHmiState } from '../hooks/useHmiState';
import {
  RotateCcw,
  ZoomIn,
  ZoomOut,
  Move,
  Users,
  Car,
  Bike,
  Heart,
  AlertTriangle,
  MapPin
} from 'lucide-react';

const Scene3D: React.FC = () => {
  const { detectedObjects, navigationInfo, vehicleStatus } = useHmiState();
  const [rotation, setRotation] = useState(0);
  const [zoom, setZoom] = useState(1);
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });

  // 处理鼠标拖拽旋转
  const handleMouseDown = (e: React.MouseEvent) => {
    setIsDragging(true);
    setDragStart({ x: e.clientX, y: e.clientY });
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging) return;
    
    const deltaX = e.clientX - dragStart.x;
    const newRotation = rotation + deltaX * 0.5;
    setRotation(newRotation);
    setDragStart({ x: e.clientX, y: e.clientY });
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  // 处理触摸旋转
  const handleTouchStart = (e: React.TouchEvent) => {
    if (e.touches.length === 1) {
      setIsDragging(true);
      setDragStart({ x: e.touches[0].clientX, y: e.touches[0].clientY });
    }
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isDragging || e.touches.length !== 1) return;
    
    const deltaX = e.touches[0].clientX - dragStart.x;
    const newRotation = rotation + deltaX * 0.5;
    setRotation(newRotation);
    setDragStart({ x: e.touches[0].clientX, y: e.touches[0].clientY });
  };

  const handleTouchEnd = () => {
    setIsDragging(false);
  };

  const getObjectIcon = (type: string) => {
    switch (type) {
      case 'pedestrian':
        return <Users size={16} className="text-danger-400" />;
      case 'vehicle':
        return <Car size={16} className="text-warning-400" />;
      case 'bicycle':
        return <Bike size={16} className="text-warning-400" />;
      case 'animal':
        return <Heart size={16} className="text-danger-400" />;
      default:
        return <AlertTriangle size={16} className="text-gray-400" />;
    }
  };

  const getObjectColor = (type: string) => {
    switch (type) {
      case 'pedestrian':
        return 'border-danger-500 bg-danger-500/20';
      case 'vehicle':
      case 'bicycle':
        return 'border-warning-500 bg-warning-500/20';
      case 'animal':
        return 'border-danger-500 bg-danger-500/20';
      default:
        return 'border-gray-500 bg-gray-500/20';
    }
  };

  return (
    <div className="control-panel h-full">
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-lg font-semibold text-white">3D场景 - 深圳</h3>

        {/* 控制按钮 */}
        <div className="flex gap-2">
          <button
            onClick={() => setRotation(0)}
            className="hmi-button-secondary"
            title="重置视角"
          >
            <RotateCcw size={16} />
          </button>
          <button
            onClick={() => setZoom(Math.min(zoom + 0.2, 2))}
            className="hmi-button-secondary"
            title="放大"
          >
            <ZoomIn size={16} />
          </button>
          <button
            onClick={() => setZoom(Math.max(zoom - 0.2, 0.5))}
            className="hmi-button-secondary"
            title="缩小"
          >
            <ZoomOut size={16} />
          </button>
        </div>
      </div>

      {/* 3D场景容器 - 支持触屏旋转交互 */}
      <div 
        className="relative bg-gradient-to-b from-gray-800 to-gray-900 rounded-lg h-[calc(100%-120px)] overflow-hidden cursor-grab active:cursor-grabbing"
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseUp}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {/* 网格背景 */}
        <div className="absolute inset-0 opacity-20">
          <svg width="100%" height="100%" className="text-gray-600">
            <defs>
              <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
                <path d="M 20 0 L 0 0 0 20" fill="none" stroke="currentColor" strokeWidth="0.5"/>
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#grid)" />
          </svg>
        </div>

        {/* 道路和车道线 - 深圳场景 */}
        <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2">
          <div className="w-96 h-2 bg-gray-600 rounded-full">
            <div className="w-full h-0.5 bg-warning-400 rounded-full animate-pulse" />
          </div>
          {/* 车道线 */}
          <div className="absolute top-0 left-1/2 transform -translate-x-1/2 w-0.5 h-2 bg-white opacity-60" />
        </div>

        {/* 红绿灯 - 使用SVG代替 */}
        <div className="absolute top-16 right-16">
          <div className="bg-gray-800 p-2 rounded">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="8" y="4" width="8" height="16" rx="2" fill="#333"/>
              <circle cx="12" cy="19" r="2" fill="#10B981"/>
              <circle cx="12" cy="12" r="2" fill="#6B7280" opacity="0.3"/>
              <circle cx="12" cy="7" r="2" fill="#6B7280" opacity="0.3"/>
            </svg>
          </div>
        </div>

        {/* RSA交通标志 */}
        <div className="absolute top-20 left-16">
          <div className="bg-yellow-500 text-black px-2 py-1 rounded text-xs font-bold">
            RSA
          </div>
        </div>

        {/* 深圳地标建筑 */}
        <div className="absolute top-8 left-1/4">
          <div className="bg-blue-600 w-4 h-8 rounded-t">
            <div className="text-xs text-white text-center mt-1">企鹅岛</div>
          </div>
        </div>

        <div className="absolute top-12 right-1/4">
          <div className="bg-green-600 w-4 h-6 rounded-t">
            <div className="text-xs text-white text-center mt-1">地铁站</div>
          </div>
        </div>

        <div className="absolute bottom-20 left-1/3">
          <div className="bg-purple-600 w-5 h-10 rounded-t">
            <div className="text-xs text-white text-center mt-1">软通动力大厦</div>
          </div>
        </div>

        <div className="absolute bottom-16 right-1/3">
          <div className="bg-orange-600 w-4 h-8 rounded-t">
            <div className="text-xs text-white text-center mt-1">滨海大厦</div>
          </div>
        </div>

        {/* 自车（居中） */}
        <div className="absolute bottom-16 left-1/2 transform -translate-x-1/2">
          <div
            className="w-8 h-16 bg-primary-500 rounded-lg border-2 border-primary-400 transform transition-transform duration-1000"
            style={{ transform: `rotate(${rotation}deg) scale(${zoom})` }}
          >
            <div className="w-2 h-2 bg-white rounded-full absolute top-1 left-1/2 transform -translate-x-1/2" />
            <div className="text-xs text-white font-bold absolute bottom-1 left-1/2 transform -translate-x-1/2">
              我车
            </div>
          </div>
        </div>

        {/* 检测到的物体 */}
        {detectedObjects.map((obj) => (
          <div
            key={obj.id}
            className={`absolute border-2 rounded-full w-6 h-6 flex items-center justify-center transition-all duration-500 ${getObjectColor(obj.type)}`}
            style={{
              left: `${50 + obj.position.x * 3}%`,
              top: `${60 + obj.position.y * 2}%`,
              transform: `scale(${zoom})`,
            }}
          >
            {getObjectIcon(obj.type)}
          </div>
        ))}

        {/* 导航路径 */}
        <div className="absolute top-4 left-4">
          <div className="glass-panel p-3">
            <div className="flex items-center gap-2 mb-2">
              <MapPin size={16} className="text-primary-400" />
              <span className="text-sm text-white font-medium">导航路径</span>
            </div>
            <div className="text-xs text-gray-300 space-y-1">
              <div>当前位置: {navigationInfo.currentStreet}</div>
              <div>下一指示: {navigationInfo.nextTurn}</div>
              <div>距离: {navigationInfo.turnDistance}m</div>
            </div>
          </div>
        </div>

        {/* 速度和状态指示器 */}
        <div className="absolute top-4 right-4">
          <div className="glass-panel p-3">
            <div className="flex items-center gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-white">{vehicleStatus.speed}</div>
                <div className="text-xs text-gray-400">km/h</div>
              </div>
              <div className="text-center">
                <div className={`w-3 h-3 rounded-full ${
                  vehicleStatus.autonomousMode ? 'bg-success-500' : 'bg-gray-500'
                }`} />
                <div className="text-xs text-gray-400 mt-1">
                  {vehicleStatus.autonomousMode ? '自动' : '手动'}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 场景信息 */}
        <div className="absolute bottom-4 left-4">
          <div className="glass-panel p-3">
            <div className="text-xs text-gray-300 space-y-1">
              <div>场景: 深圳滨海大道</div>
              <div>天气: 晴朗</div>
              <div>时间: {new Date().toLocaleTimeString('zh-CN')}</div>
            </div>
          </div>
        </div>

        {/* 检测对象信息 */}
        {detectedObjects.length > 0 && (
          <div className="absolute bottom-4 right-4">
            <div className="glass-panel p-3">
              <div className="text-xs text-gray-300 mb-2">检测对象</div>
              <div className="space-y-1">
                {detectedObjects.slice(0, 3).map((obj) => (
                  <div key={obj.id} className="flex items-center gap-2">
                    {getObjectIcon(obj.type)}
                    <span className="text-xs text-white">
                      {obj.distance}m
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 底部控制栏 */}
      <div className="mt-4 flex justify-center gap-4">
        <button className="hmi-button-secondary text-sm">
          <Move size={16} className="mr-2" />
          拖拽视图
        </button>
        <button className="hmi-button-secondary text-sm">
          场景重置
        </button>
        <button className="hmi-button-secondary text-sm">
          视角切换
        </button>
      </div>
    </div>
  );
};

export default Scene3D;
